<template>
  <div class="app-container">

    <!-- 查询条件 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="100px" v-if="showSearch">
      <el-form-item label="制单日期">
        <el-date-picker
          v-model="valueTime"
          type="daterange"
          range-separator="—"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          clearable
        />
      </el-form-item>
      <el-form-item label="支付时间">
        <el-date-picker
          v-model="payTime"
          type="daterange"
          range-separator="—"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          clearable
        />
      </el-form-item>
      <el-form-item label="店铺名称">
        <el-select v-model="queryParams.shopId" placeholder="请选择店铺" clearable>
          <el-option v-for="item in shopList" :key="item.id" :label="item.shopName" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="会员名称">
        <el-input v-model="queryParams.clientName" placeholder="请输入会员名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="平台单号">
        <el-input v-model="queryParams.platformOrderCode" placeholder="请输入平台单号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="订单编号">
        <el-input v-model="queryParams.orderCode" placeholder="请输入订单编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="发货状态">
        <el-select v-model="queryParams.deliveryStatus" placeholder="请选择发货状态" clearable>
          <el-option v-for="item in dict.type.ship_status" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="配货状态">
        <el-select v-model="queryParams.prepareStatus" placeholder="请选择配货状态" clearable>
          <el-option v-for="item in dict.type.prepare_status" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="物流单号">
        <el-input v-model="queryParams.expressNo" placeholder="请输入物流单号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="卖家备注">
        <el-input v-model="queryParams.sellerRemark" placeholder="请输入卖家备注" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="订单状态">
        <!-- 可多选 -->
        <el-select v-model="orderStatus" placeholder="请选择订单状态" clearable multiple>
           <el-option
              v-for="dict in dict.type.order_progress"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
        </el-select>
      </el-form-item>
      <el-form-item label="打印状态">
        <el-select v-model="queryParams.printStatus" placeholder="请选择打印状态" clearable>
          <el-option v-for="item in dict.type.print_status" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="拦截">
        <!-- 勾选值是1，不勾选值是0 -->
        <el-checkbox v-model="intercepted" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 表格功能 -->
    <el-row :gutter="10" class="mb8">
      <!-- v-hasPermi="['mes:pro:process:edit']" -->
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-edit"
          size="mini"
          @click="handleEdit"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          size="mini"
          @click="handleEnable('copy')"
        >复制</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          size="mini"
          @click="handleEnable('audit')"
        >审核</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          plain
          size="mini"
          @click="handleEnable('auditFalse')"
        >反审核</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-close"
          size="mini"
          @click="handleCancelOrder"
        >作废</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleEnable('import')"
        >订单导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-dropdown @command="handleInterceptCommand">
          <el-button
            plain
            size="mini"
          >订单拦截<i class="el-icon-arrow-down el-icon--right"></i></el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="intercept">拦截</el-dropdown-item>
            <el-dropdown-item command="cancelIntercept">取消拦截</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </el-col>
      <el-col :span="1.5">
        <el-dropdown @command="handleBatchCommand">
          <el-button
            plain
            size="mini"
          >批量操作<i class="el-icon-arrow-down el-icon--right"></i></el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="warehouse">修改仓库</el-dropdown-item>
            <el-dropdown-item command="express">修改物流公司</el-dropdown-item>
            <el-dropdown-item command="stock">转为现货订单</el-dropdown-item>
            <el-dropdown-item command="bizUser">修改业务员</el-dropdown-item>
            <el-dropdown-item command="extInfo">修改附加信息</el-dropdown-item>
            <el-dropdown-item command="predictDeliveryTime">修改预计发货时间</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </el-col>
      <right-toolbar 
        :showSearch.sync="showSearch" 
        @queryTable="getList"
      />
    </el-row>

    <!-- 批量操作弹窗 -->
    <el-dialog :visible.sync="batchDialog.visible" :title="batchDialog.type==='warehouse'?'批量修改仓库':batchDialog.type==='express'?'批量修改物流公司':batchDialog.type==='stock'?'批量转为现货订单':batchDialog.type==='bizUser'?'批量修改业务员':batchDialog.type==='extInfo'?'批量修改附加信息':batchDialog.type==='predictDeliveryTime'?'批量修改预计发货时间':''" width="400px" @close="handleBatchCancel">
      <el-form v-if="batchDialog.type==='warehouse'" label-width="100px">
        <el-form-item label="新仓库名称">
          <el-input v-model="batchForm.warehouseName" placeholder="请输入新仓库名称" />
        </el-form-item>
      </el-form>
      <el-form v-if="batchDialog.type==='express'" label-width="100px">
        <el-form-item label="新物流公司">
          <el-input v-model="batchForm.expressCompany" placeholder="请输入新物流公司" />
        </el-form-item>
      </el-form>
      <div v-if="batchDialog.type==='stock'" style="padding: 20px 0; text-align: center;">确定将选中订单转为现货订单？</div>
      <el-form v-if="batchDialog.type==='bizUser'" label-width="100px">
        <el-form-item label="新业务员">
          <el-select v-model="batchForm.bizUser" placeholder="请选择业务员" filterable>
            <el-option v-for="item in userList" :key="item.nickName" :label="item.nickName" :value="item.nickName" />
          </el-select>
        </el-form-item>
      </el-form>
      <el-form v-if="batchDialog.type==='extInfo'" label-width="100px">
        <el-form-item label="附加信息">
          <el-input v-model="batchForm.extInfo" type="textarea" placeholder="请输入附加信息" />
        </el-form-item>
      </el-form>
      <el-form v-if="batchDialog.type==='predictDeliveryTime'" label-width="120px">
        <el-form-item label="预计发货时间">
          <el-date-picker v-model="batchForm.predictDeliveryTime" type="datetime" placeholder="请选择预计发货时间" value-format="yyyy-MM-dd HH:mm:ss" style="width:100%" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleBatchSubmit">确 定</el-button>
        <el-button @click="handleBatchCancel">取 消</el-button>
      </div>
      <div class="upload-area" v-if="batchDialog.type === 'import'">
        <el-upload
          ref="upload"
          :limit="1"
          accept=".xlsx,.xls"
          :show-file-list="false"
          :http-request="handleImportUpload"
          drag
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip " slot="tip">
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
          </div>
        </el-upload>
      </div>
    </el-dialog>

    <!-- 表格信息、分页 -->
    <div class="app-container-main">
      
      <vxe-table
        border
        stripe
        v-loading="loading" 
        ref="tableRef"
        size="small"
        header-align="center"
        :row-config="rowConfig"
        :column-config="columnConfig"
        @checkbox-change="checkboxChangeEvent"
        @checkbox-all="checkboxAll"
        @cell-click="cellClickEvent"
        :data="tableData"
      >
        <vxe-column type="checkbox" width="80" fixed="left" drag-sort />
        <vxe-column type="seq" title="序号" width="60" fixed="left" align="center" />
        <vxe-column field="orderCode" title="订单编号" width="150" fixed="left" align="center" show-overflow="title" />
        <vxe-column field="orderType" title="订单类型" width="100" align="center" show-overflow="title" />
        <vxe-column field="platformOrderCode" title="平台单号" width="150" align="center" show-overflow="title" />
        <vxe-column field="platformName" title="订单来源" width="100" align="center" show-overflow="title" />
        <vxe-column field="shopName" title="店铺名称" width="120" align="center" show-overflow="title" />
        <vxe-column field="orderStatusDesc" title="订单状态" width="100" align="center" show-overflow="title" />
        <vxe-column field="tradeStatus" title="平台交易状态" width="120" align="center" show-overflow="title" />
        <vxe-column field="orderTime" title="拍单日期" width="120" align="center" show-overflow="title" />
        <vxe-column field="createTime" title="制单日期?" width="120" align="center" show-overflow="title" />
        <vxe-column field="bizUser" title="业务员" width="100" align="center" show-overflow="title" />
        <vxe-column field="payTime" title="支付时间" width="120" align="center" show-overflow="title" />
        <vxe-column field="totalPrice" title="订单金额" width="120" align="center" show-overflow="title" />
        <vxe-column field="yieldAmount" title="让利金额" width="100" align="center" show-overflow="title" />
        <vxe-column field="payAmount" title="支付金额" width="120" align="center" show-overflow="title" />
        <vxe-column field="refund" title="退款金额" width="100" align="center" show-overflow="title" />
        <vxe-column field="orderCount" title="商品数量？" width="100" align="center" show-overflow="title" />
        <vxe-column field="buyerRemark" title="买家留言" width="150" align="center" show-overflow="title" />
        <vxe-column field="sellerRemark" title="卖家备注" width="150" align="center" show-overflow="title" />
        <vxe-column field="secRemark" title="二次备注" width="150" align="center" show-overflow="title" />
        <vxe-column field="extInfo" title="附加信息" width="150" align="center" show-overflow="title" />
        <vxe-column field="clientName" title="会员名称" width="120" align="center" show-overflow="title" />
        <vxe-column field="clientId" title="会员代码?" width="120" align="center" show-overflow="title" />
        <vxe-column field="refundStatus" title="是否退款" width="100" align="center" show-overflow="title" />
        <vxe-column field="consignee" title="收货人" width="100" align="center" show-overflow="title" />
        <vxe-column field="address" title="收货信息" width="200" align="center" show-overflow="title" />
        <vxe-column field="suggestExpress" title="建议快递/物流" width="120" align="center" show-overflow="title" />
        <vxe-column field="auditStatus" title="审核状态?" width="100" align="center" show-overflow="title" />
        <vxe-column field="prepareStatus" title="配货状态" width="100" align="center" show-overflow="title" />
        <vxe-column field="financeStatus" title="财审状态？" width="100" align="center" show-overflow="title" />
        <vxe-column field="deliveryStatus" title="发货状态" width="100" align="center" show-overflow="title" />
        <vxe-column field="collect" title="货到付款" width="100" align="center" show-overflow="title" >
          <template #default="{ row }">
            <span>{{ row.collect === '1' ? '是' : '否' }}</span>
          </template>
        </vxe-column>
      </vxe-table>

      <pagination
        v-show="total>=0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <!-- 底部tab -->
    <div class="app-container-footer">
      <el-tabs v-model="activeName" type="border-card" :lazy="true">
          <el-tab-pane label="销售订单明细" name="1"><property :cellId="cellId" :rowData="rowData" /></el-tab-pane>
          <el-tab-pane label="商品明细" name="2"><goods :cellId="cellId" :readonly="true" /></el-tab-pane>
          <el-tab-pane label="支付明细" name="3"><payInfo :cellId="cellId" :readonly="true" /></el-tab-pane>
          <!-- <el-tab-pane label="发票信息" name="4"><invoice :cellId="cellId" /></el-tab-pane> -->
          <el-tab-pane label="收货信息" name="5"><Address :cellId="cellId" :readonly="true" /></el-tab-pane>
          <el-tab-pane label="物流跟踪" name="6"><logistics :cellId="cellId" /></el-tab-pane> 
          <el-tab-pane label="发货信息" name="7"><ShippingInfo :cellId="cellId" /></el-tab-pane>
          <el-tab-pane label="操作日志" name="8"><operation :cellId="cellId" /></el-tab-pane>
      </el-tabs>
      
    </div>

    <!-- 新增弹窗 -->
    <el-dialog :title="title" :close-on-click-modal="false" :visible.sync="open" width="80%" append-to-body @close="cancel" > 
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="店铺名称" prop="shopId" >
              <el-select v-model="form.shopId" placeholder="请选择店铺" filterable>
                <el-option v-for="item in shopList" :key="item.id" :label="item.shopName" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="订单类型" prop="orderType" >
              <el-select v-model="form.orderType" placeholder="请选择订单类型" filterable allow-create :default-first-option="true">
                <el-option v-for="item in dict.type.order_type" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="拍单日期" prop="orderTime" >
              <el-date-picker v-model="form.orderTime" type="date" placeholder="请选择拍单日期" value-format="yyyy-MM-dd HH:mm:ss" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="平台单号" prop="platformOrderCode" >
              <el-input v-model="form.platformOrderCode" placeholder="未填写自动生成" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="仓库名称" prop="warehouseName" >
              <el-select v-model="form.warehouseName" placeholder="请选择仓库" filterable>
                <el-option v-for="item in warehouseList" :key="item.warehouseName" :label="item.warehouseName" :value="item.warehouseName" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="业务员" prop="bizUser">
              <el-select v-model="form.bizUser" placeholder="请选择业务员" filterable>
                <el-option v-for="item in userList" :key="item.nickName" :label="item.nickName" :value="item.nickName" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="物流公司" prop="suggestExpress">
              <el-select v-model="form.suggestExpress" placeholder="请选择物流公司" filterable>
                <el-option v-for="item in logisticsCompanyList" :key="item.id" :label="item.platformName" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="物流费用" prop="expressFee">
              <el-input-number v-model="form.expressFee" :min="0" :precision="2" placeholder="请输入物流费用" style="width:100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="订单来源" prop="platformId">
              <el-select v-model="form.platformId" placeholder="请选择订单来源" filterable>
                <el-option v-for="item in orderTypeList" :key="item.id" :label="item.platformName" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="会员名称" prop="clientName">
              <el-input v-model="form.clientName" placeholder="请输入会员名称" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="货到付款" prop="collect">
              <el-select v-model="form.collect" placeholder="请选择">
                <el-option label="否" value="否" />
                <el-option label="是" value="是" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="买家留言" prop="buyerRemark">
              <el-input v-model="form.buyerRemark" type="textarea" placeholder="请输入买家留言" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="卖家备注" prop="sellerRemark">
              <el-input v-model="form.sellerRemark" type="textarea" placeholder="请输入卖家备注" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="二次备注" prop="secRemark">
              <el-input v-model="form.secRemark" type="textarea" placeholder="请输入二次备注" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="附加信息" prop="extInfo">
              <el-input v-model="form.extInfo" type="textarea" placeholder="请输入附加信息" />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 商品信息tab、支付信息tab、收货信息tab后续补充  -->
      </el-form>
      <el-tabs v-model="addTabActive" type="card" style="margin-top: 20px;">
        <el-tab-pane label="商品信息" name="goods">
          <goods ref="goodsTab" :cellId="cellId" :warehouseList="warehouseList" />
        </el-tab-pane>

        <el-tab-pane label="支付信息" name="pay">
          <payInfo ref="payTab" :cellId="cellId" />
        </el-tab-pane>

        <el-tab-pane label="收货信息" name="address">
          <Address ref="addressTab" :cellId="cellId" />
        </el-tab-pane>
      </el-tabs>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">保存</el-button>
        <el-button @click="cancel">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { 
    addSalesOrder,
    listSalesOrder,
    editSalesOrder,
    orderAudit,
    updateWarehouse,
    updateExpress,
    updateStock,
    importSellOrder,
    deleteOrder,
    cancelOrder,
    interceptOrder,
    cancelInterceptOrder,
    editBizUser,
    editExtInfo,
    editPDT,
    getSalesOrderDetail
  } from "@/api/mes/sales/saleOrder";
import { listWarehouse } from "@/api/mes/wm/warehouse";
import { listShopBasic } from "@/api/mes/sales/shopBasic";
import { listUser } from "@/api/system/user";
import { listPlatforms } from "@/api/mes/sales/platform";
import property from "./components/property.vue";
import Address from "./components/address.vue";
import goods from "./components/goods.vue";
import invoice from "./components/invoice.vue";
import logistics from "./components/logistics.vue";
import operation from "./components/operation.vue";
import payInfo from "./components/payInfo.vue";
import ShippingInfo from "./components/shippingInfo.vue";

export default {
  name: 'Order',
  dicts: ['order_progress', 'order_type', 'ship_status', 'prepare_status', 'platform_type', 'print_status'],
  components: {
    property,
    Address,
    goods,
    invoice,
    logistics,
    operation,
    payInfo,
    ShippingInfo
  },
  data() {
    return {
      showSearch: true,
      addTabActive: 'goods',
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      tableData: [],
      total: 0,
      titleList:[
        {name: '销售订单明细', id: 1},
        {name: '商品明细', id: 2},
        {name: '累计消费', id: 3},
        {name: '支付明细', id: 4},
        {name: '收货信息', id: 5},
        {name: '物流跟踪', id: 6},
        {name: '发货信息', id: 7},
        {name: '操作日志', id: 8},
      ],
      columnConfig: {
        drag: true,
        resizable: true,
        storage: true,
        sortConfig: {
          trigger: 'cell',
          remote: true
        },
        align: 'center',
        headerAlign: 'center'
      },
      rowConfig: {
        drag: true,
        keyField: 'id',
        isHover: true,
        isCurrent: true,
      },
      activeName: '1',
      activeIndex: 1,
      loading: false,
      valueTime: this.getDefaultDateRange(),
      payTime: null,
      cellId: '',
      title:'',
      open: false,
      form:{},
      rules: {
        shopId: [{ required: true, message: '请选择店铺', trigger: 'blur' }],
        orderType: [{ required: true, message: '请选择订单类型', trigger: 'blur' }],
        orderTime: [{ required: true, message: '请选择拍单日期', trigger: 'blur' }],
        warehouseName: [{ required: true, message: '请选择仓库', trigger: 'blur' }],
      },
      userList:[],
      ids: [],
      batchDialog: {
        visible: false,
        type: '', // warehouse, express, stock
      },
      batchForm: {
        warehouseName: '',
        expressCompany: '',
        bizUser: '',
        extInfo: '',
        predictDeliveryTime: ''
      },
      isUploading: false,
      intercepted: false,
      warehouseList: [],
      shopList: [],
      logisticsCompanyList: [],
      orderTypeList: [],
      rowData: {},
      orderStatus: [],
    }
  },
  created() {
    this.getList()
    listUser({ pageNum: 1, pageSize: 9999, roleName:'电商业务员'}).then(response => {
      this.userList = response.rows;
    });
    this.getShopList();
    this.getWarehouseList();
  },
  methods: {

    // 获取物流公司
    getLogisticsCompanyList(){
      listPlatforms({
        platformType: this.dict.type.platform_type.filter(item => item.label === '物流平台')[0].value,
        enabled: 1,
        pageNum: 1,
        pageSize: 9999,
      }).then(response => {
        this.logisticsCompanyList = response.rows;
      })
    },
    // 获取订单来源数据
    getOrderTypeList(){
      listPlatforms({
        platformType: this.dict.type.platform_type.filter(item => item.label === '电商平台')[0].value,
        enabled: 1,
        pageNum: 1,
        pageSize: 9999,
      }).then(response => {
        this.orderTypeList = response.rows;
      })
    },
    // 仓库下拉数据
    getWarehouseList(){
      listWarehouse({
        pageNum: 1,
        pageSize: 9999,
      }).then(response => {
        this.warehouseList = response.rows;
      })
    },
    // 店铺下拉数据
    getShopList(){
      listShopBasic({
        enabled: 1,
        pageNum: 1,
        pageSize: 9999
      }).then(response => {
        this.shopList = response.rows;
      })
    },
    
    handleBatchCommand(type) {
      if (this.ids.length === 0) {
        this.$modal.msgError("请选择数据");
        return;
      }
      this.batchDialog.type = type;
      this.batchDialog.visible = true;
      // 清空表单
      this.batchForm = { 
        warehouseName: '', 
        expressCompany: '', 
        bizUser: '', 
        extInfo: '', 
        predictDeliveryTime: '' 
      };
    },

    handleBatchSubmit() {
      if (this.batchDialog.type === 'warehouse') {
        if (!this.batchForm.warehouseName) {
          this.$modal.msgError('请输入新仓库名称');
          return;
        }
        const params = {
          warehouseName: this.batchForm.warehouseName,
          orderIds: this.ids
        };
        this.loading = true;
        updateWarehouse(params)
          .then(() => {
            this.$modal.msgSuccess('批量修改仓库成功');
            this.batchDialog.visible = false;
            this.getList();
          })
          .catch(() => {
            this.$modal.msgError('批量修改仓库失败');
          })
          .finally(() => {
            this.loading = false;
          });
        return;
      }
      if (this.batchDialog.type === 'express') {
        if (!this.batchForm.expressCompany) {
          this.$modal.msgError('请输入新物流公司');
          return;
        }
        const params = {
          expressCompany: this.batchForm.expressCompany,
          orderIds: this.ids
        };
        this.loading = true;
        updateExpress(params)
          .then(() => {
            this.$modal.msgSuccess('批量修改物流公司成功');
            this.batchDialog.visible = false;
            this.getList();
          })
          .catch(() => {
            this.$modal.msgError('批量修改物流公司失败');
          })
          .finally(() => {
            this.loading = false;
          });
        return;
      }
      if (this.batchDialog.type === 'stock') {
        const params = {
          orderIds: this.ids,
          inStock: true
        };
        this.loading = true;
        updateStock(params)
          .then(() => {
            this.$modal.msgSuccess('批量转为现货订单成功');
            this.batchDialog.visible = false;
            this.getList();
          })
          .catch(() => {
            this.$modal.msgError('批量转为现货订单失败');
          })
          .finally(() => {
            this.loading = false;
          });
        return;
      }
      if (this.batchDialog.type === 'bizUser') {
        if (!this.batchForm.bizUser) {
          this.$modal.msgError('请选择业务员');
          return;
        }
        const params = {
          bizUser: this.batchForm.bizUser,
          orderIds: this.ids
        };
        this.loading = true;
        editBizUser(params)
          .then(() => {
            this.$modal.msgSuccess('批量修改业务员成功');
            this.batchDialog.visible = false;
            this.getList();
          })
          .catch(() => {
            this.$modal.msgError('批量修改业务员失败');
          })
          .finally(() => {
            this.loading = false;
          });
        return;
      }
      if (this.batchDialog.type === 'extInfo') {
        if (!this.batchForm.extInfo) {
          this.$modal.msgError('请输入附加信息');
          return;
        }
        const params = {
          extInfo: this.batchForm.extInfo,
          orderIds: this.ids
        };
        this.loading = true;
        editExtInfo(params)
          .then(() => {
            this.$modal.msgSuccess('批量修改附加信息成功');
            this.batchDialog.visible = false;
            this.getList();
          })
          .catch(() => {
            this.$modal.msgError('批量修改附加信息失败');
          })
          .finally(() => {
            this.loading = false;
          });
        return;
      }
      if (this.batchDialog.type === 'predictDeliveryTime') {
        if (!this.batchForm.predictDeliveryTime) {
          this.$modal.msgError('请选择预计发货时间');
          return;
        }
        const params = {
          predictDeliveryTime: this.batchForm.predictDeliveryTime,
          orderIds: this.ids
        };
        this.loading = true;
        editPDT(params)
          .then(() => {
            this.$modal.msgSuccess('批量修改预计发货时间成功');
            this.batchDialog.visible = false;
            this.getList();
          })
          .catch(() => {
            this.$modal.msgError('批量修改预计发货时间失败');
          })
          .finally(() => {
            this.loading = false;
          });
        return;
      }
    },

    handleBatchCancel() {
      this.batchDialog.visible = false;
    },
    getDefaultDateRange() {
      const today = new Date();
      const thirtyDaysAgo = new Date();
      thirtyDaysAgo.setDate(today.getDate() - 7);
      const formatDate = (date) => {
          const year = date.getFullYear();
          const month = String(date.getMonth() + 1).padStart(2, '0');
          const day = String(date.getDate()).padStart(2, '0');
          return `${year}-${month}-${day}`;
      };
      return [formatDate(thirtyDaysAgo), formatDate(today)];
    },
    getList(){
      this.loading = true;
      if(this.valueTime && this.valueTime.length > 0){
        this.queryParams.startDate = this.valueTime[0]
        this.queryParams.endDate = this.valueTime[1]
      }
      if(this.payTime && this.payTime.length > 0){
        this.queryParams.payStartDate = this.payTime[0] 
        this.queryParams.payEndDate = this.payTime[1]
      }
      if(this.orderStatus && this.orderStatus.length > 0){
        this.queryParams.orderStatus = this.orderStatus.join(',')
      }else{
        this.queryParams.orderStatus = null
      }
      this.queryParams.intercepted = this.intercepted ? 1 : 0;
      listSalesOrder(this.queryParams).then(response => {
        this.tableData = response.rows || [];
        this.$nextTick(() => {
          if (this.tableData.length > 0) {
            this.$refs.tableRef.setCurrentRow(this.tableData[0]);
            this.cellId = this.tableData[0].id;
            this.rowData = this.tableData[0];
          } else {
            this.cellId = ''; 
            this.rowData = {};
          }
        })
        this.total = response.total || 0;
        console.log(response);
      }).finally(() => {
        this.loading = false;
      })
    },
    reset(){
      this.form = {
        collect: '否',
      };
      this.autoGenFlag = false;
      // this.$refs.form.resetFields();
    },
    handleAdd(){
      this.open = true;
      this.title = '新增';
      this.cellId = 'add';
      this.form = {
        collect: '否',
      };
      // this.reset();
      this.getLogisticsCompanyList();
      this.getOrderTypeList();
    },  

    // 修改功能：选中一条数据，获取详情，弹窗回显，保存时调editSalesOrder
    async handleEdit() {
      if (!this.ids || this.ids.length !== 1) {
        this.$modal.msgError('请选择一条要编辑的数据');
        return;
      }
      this.getLogisticsCompanyList();
      this.getOrderTypeList();
      const id = this.ids[0];
      try {
        const { data } = await getSalesOrderDetail(id)
        // 回显主表单
        this.cellId = id;
        this.form = { ...data };
        this.form.suggestExpress = this.form.suggestExpress ? Number(this.form.suggestExpress) : null;
        this.form.collect = this.form.collect == 1 ? '是' : '否';
        this.title = '修改';
        this.open = true;
      } catch (e) {
        this.$modal.msgError('获取订单详情失败');
      }
    },
    handleDelete(row){
      if(this.ids.length==0){
        this.$modal.msgError("请选择要删除的数据");
        return;
      }
      const ids = this.ids;
      this.$modal.confirm('是否确认删除选中的订单？').then(() => {
        return deleteOrder(ids);
      }).then(() => {
        this.getList();
        this.ids = [];
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    async handleEnable(action) {
      if (this.ids.length === 0 && action !== 'import') {
        this.$modal.msgError("请选择数据");
        return;
      }
      if (action === 'copy') {
        // 只允许复制一条数据
        if (this.ids.length !== 1) {
          this.$modal.msgError('仅允许复制一条数据');
          return;
        }
        this.getLogisticsCompanyList();
        this.getOrderTypeList();
        const id = this.ids[0];
        this.cellId = id;
        try {
          const { data } = await getSalesOrderDetail(id)
          // 回显主表单
          this.form = { ...data };
          this.form.orderCode = null; // 复制，订单编号置空
          this.form.suggestExpress = this.form.suggestExpress ? Number(this.form.suggestExpress) : null;
          this.form.collect = this.form.collect == 1 ? '是' : '否';
          this.title = '复制';
          this.open = true;
        } catch (e) {
          this.$modal.msgError('获取订单详情失败');
        }
        return;
      }
      if (action === 'audit' || action === 'auditFalse') {
        const ok = action === 'audit';
        this.$modal.confirm('是否确认' + (ok ? '审核' : '反审核') + '选中的订单？').then(() => {
          orderAudit({ ok, orderIds :this.ids}).then(() => {
            this.$modal.msgSuccess('操作成功');
            this.getList();
          })
        }).catch(() => {});
        return;
      }
      // 订单导入弹窗已集成el-upload，无需再触发input
      if (action === 'import') {
        this.batchDialog.type = 'import';
        this.batchDialog.visible = true;
        return;
      }
    },
    // 订单导入el-upload自定义上传
    handleImportUpload(param) {
      if (!param.file) return;
      const formData = new FormData();
      formData.append('file', param.file);
      this.loading = true;
      importSellOrder(formData)
        .then(res => {
          this.$modal.msgSuccess('导入成功');
          this.batchDialog.visible = false;
          this.getList();
        })
        .catch(() => {
          this.$modal.msgError('导入失败');
        })
        .finally(() => {
          this.loading = false;
        });
    },
    handleQuery(){
      this.getList();
    },
    resetQuery(){
      this.resetForm("queryForm");
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        poCode: null,
        vendorNick: null,
      };
      this.orderStatus = [];
      this.intercepted = false;
      this.payTime = null;
      this.valueTime = this.getDefaultDateRange()
      this.getList();
    },
    submitForm(){
      this.$refs["form"].validate(async valid => {
        if (valid) {
          // 进行额外的校验
          const validationResult = await this.validateAllRequiredFields();
          if (!validationResult.isValid) {
            this.$modal.msgError(validationResult.message);
            return;
          }

          const saleOrder = {
            ...this.form,
            collect: this.form.collect === '是' ? 1 : 0,
          }
          // 统一收集弹窗内所有表单数据
          // 商品信息，补充自动计算字段
          let saleOrderProductList = this.$refs.goodsTab && this.$refs.goodsTab.tableData ? JSON.parse(JSON.stringify(this.$refs.goodsTab.tableData)) : [];
          // 获取商品tab内自动计算方法
          const goodsTab = this.$refs.goodsTab;
          if (goodsTab && Array.isArray(saleOrderProductList)) {
            saleOrderProductList = saleOrderProductList.map(row => {
              // 兼容组件内methods
              let stdAmount = row.stdAmount;
              let actualAmount = row.actualAmount;
              let profitAmount = row.profitAmount;
              if (typeof goodsTab.calcStdAmount === 'function') {
                stdAmount = goodsTab.calcStdAmount(row);
              }
              if (typeof goodsTab.calcActualAmount === 'function') {
                actualAmount = goodsTab.calcActualAmount(row);
              }
              if (typeof goodsTab.calcProfitAmount === 'function') {
                profitAmount = goodsTab.calcProfitAmount(row);
              }
              return {
                ...row,
                stdAmount,
                actualAmount,
                profitAmount
              };
            });
          }
          // 支付信息
          const saleOrderPayList = this.$refs.payTab && this.$refs.payTab.tableData ? JSON.parse(JSON.stringify(this.$refs.payTab.tableData)) : [];
          // 收货信息
          let saleOrderDelivery = {};
          if (this.$refs.addressTab && this.$refs.addressTab.form) {
            saleOrderDelivery = JSON.parse(JSON.stringify(this.$refs.addressTab.form));
          } else if (this.$refs.addressTab && this.$refs.addressTab.$refs && this.$refs.addressTab.$refs.form && this.$refs.addressTab.$refs.form.model) {
            // 兼容el-form嵌套
            saleOrderDelivery = JSON.parse(JSON.stringify(this.$refs.addressTab.$refs.form.model));
          }
          // 组装到form对象
          const submitData = {
            saleOrder,
            saleOrderProductList,
            saleOrderPayList,
            saleOrderDelivery
          };
          // 判断是新增/修改/复制
          if(this.title === '复制'){
            // 复制
            addSalesOrder(submitData).then(response => {
              this.$modal.msgSuccess("复制成功");
              this.open = false;
              this.getList();
            });
          } else if (saleOrder.id != null) {
            // 修改
            editSalesOrder(submitData).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            // 新增
            addSalesOrder(submitData).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      })
    },

    // 校验所有必填项
    async validateAllRequiredFields() {
      try {
        // 1. 校验商品信息
        const goodsValidation = this.validateGoodsInfo();
        if (!goodsValidation.isValid) {
          return goodsValidation;
        }

        // 2. 校验收货信息
        const addressValidation = await this.validateAddressInfo();
        if (!addressValidation.isValid) {
          return addressValidation;
        }

        // 3. 校验支付信息（可选，根据业务需求）
        const payValidation = this.validatePayInfo();
        if (!payValidation.isValid) {
          return payValidation;
        }

        return { isValid: true, message: '' };
      } catch (error) {
        console.error('校验过程中出现错误:', error);
        return { isValid: false, message: '校验过程中出现错误，请重试' };
      }
    },

    // 校验商品信息
    validateGoodsInfo() {
      const goodsTab = this.$refs.goodsTab;
      if (!goodsTab || !goodsTab.tableData || goodsTab.tableData.length === 0) {
        return { isValid: false, message: '请至少添加一个商品' };
      }

      for (let i = 0; i < goodsTab.tableData.length; i++) {
        const row = goodsTab.tableData[i];
        const rowNum = i + 1;

        // 必填字段校验
        if (!row.productCode || row.productCode.trim() === '') {
          return { 
            isValid: false, 
            message: `第${rowNum}行商品：请选择商品编码` 
          };
        }

        if (!row.platformProductCode || row.platformProductCode.trim() === '') {
          return { 
            isValid: false, 
            message: `第${rowNum}行商品：请选择平台商品编码` 
          };
        }

        // if (!row.warehouseName || row.warehouseName.trim() === '') {
        //   return { 
        //     isValid: false, 
        //     message: `第${rowNum}行商品：请选择仓库名称` 
        //   };
        // }

        if (!row.quantity || row.quantity <= 0) {
          return { 
            isValid: false, 
            message: `第${rowNum}行商品：数量必须大于0` 
          };
        }

        // if (row.stdPrice === undefined || row.stdPrice === null || row.stdPrice < 0) {
        //   return { 
        //     isValid: false, 
        //     message: `第${rowNum}行商品：标准单价不能为空且不能小于0` 
        //   };
        // }

        if (row.actualPrice === undefined || row.actualPrice === null || row.actualPrice <= 0) {
          return { 
            isValid: false, 
            message: `第${rowNum}行商品：实际单价必须大于0` 
          };
        }

        // if (row.discount === undefined || row.discount === null || row.discount <= 0 || row.discount > 1) {
        //   return { 
        //     isValid: false, 
        //     message: `第${rowNum}行商品：折扣必须在0-1之间` 
        //   };
        // }
      }

      return { isValid: true, message: '' };
    },

    // 校验收货信息
    async validateAddressInfo() {
      const addressTab = this.$refs.addressTab;
      if (!addressTab) {
        return { isValid: false, message: '无法获取收货信息' };
      }

      let addressForm = {};
      if (addressTab.form) {
        addressForm = addressTab.form;
      } else if (addressTab.$refs && addressTab.$refs.form && addressTab.$refs.form.model) {
        addressForm = addressTab.$refs.form.model;
      }

      // 必填字段校验
      if (!addressForm.consignee || addressForm.consignee.trim() === '') {
        return { isValid: false, message: '收货信息：请输入收货人' };
      }

      if (!addressForm.phone || addressForm.phone.trim() === '') {
        return { isValid: false, message: '收货信息：请输入收货手机' };
      }

      if (!addressForm.address || addressForm.address.trim() === '') {
        return { isValid: false, message: '收货信息：请输入收货地址' };
      }

      // 手机号格式校验
      const phoneRegex = /^1[3-9]\d{9}$/;
      if (!phoneRegex.test(addressForm.phone.trim())) {
        return { isValid: false, message: '收货信息：请输入正确的手机号码' };
      }

      return { isValid: true, message: '' };
    },

    // 校验支付信息（可选）
    validatePayInfo() {
      const payTab = this.$refs.payTab;
      if (!payTab || !payTab.tableData || payTab.tableData.length === 0) {
        // 支付信息不是必填的，可以为空
        return { isValid: true, message: '' };
      }

      for (let i = 0; i < payTab.tableData.length; i++) {
        const row = payTab.tableData[i];
        const rowNum = i + 1;

        if (row.payAmount !== undefined && row.payAmount !== null && row.payAmount !== '') {
          if (row.payAmount <= 0) {
            return { 
              isValid: false, 
              message: `第${rowNum}行支付信息：支付金额必须大于0` 
            };
          }

          if (!row.payWay || row.payWay.trim() === '') {
            return { 
              isValid: false, 
              message: `第${rowNum}行支付信息：请输入支付方式` 
            };
          }
        }
      }

      return { isValid: true, message: '' };
    },

    // 订单拦截/取消拦截下拉处理
    handleInterceptCommand(type) {
      if (this.ids.length === 0) {
        this.$modal.msgError("请选择数据");
        return;
      }
      let confirmMsg = '';
      if (type === 'intercept') {
        confirmMsg = '确定要拦截选中的订单吗？';
        this.$confirm(confirmMsg).then(() => {
          interceptOrder({orderIds: this.ids}).then(response => {
            this.$modal.msgSuccess("拦截成功");
            this.getList();
          }).catch(() => {
            this.$modal.msgError("拦截失败");
          })
        })
      } else if (type === 'cancelIntercept') {
        confirmMsg = '确定要取消拦截选中的订单吗？';
        this.$confirm(confirmMsg).then(() => {
          cancelInterceptOrder({orderIds: this.ids}).then(response => {
            this.$modal.msgSuccess("取消拦截成功");
            this.getList();
          }).catch(() => {
            this.$modal.msgError("取消拦截失败");
          })
        })
      }
      
    },
    cancel(){
      this.$refs["form"].resetFields();
      this.cellId = '';
      this.open = false;
    },
    cellClickEvent({row}){
      this.cellId = row.id;
      this.rowData = row;
    },
    checkboxChangeEvent(checked){
      this.ids = checked.records.map(item => item.id)
      console.log(checked.records, this.ids);
    },
    checkboxAll(checked){
      this.ids = checked.records.map(item => item.id)
      console.log(checked.records, this.ids)
    },
    importTemplate(){
      // window.open("/excel_templates/shop_templates.xls", "_blank"); 
       this.$message.info("请联系管理员获取导入模板");
    },
    handleCancelOrder() {
      if (this.ids.length === 0) {
        this.$modal.msgError("请选择要作废的订单");
        return;
      }
      this.$modal.confirm('确定要作废选中的订单吗？').then(() => {
        return cancelOrder({
          orderIds: this.ids
        });
      }).then(() => {
        this.$modal.msgSuccess("订单作废成功");
        this.getList();
      }).catch(() => {});
    },
  }
};

</script>

<style scoped>
::v-deep.el-date-editor.el-input {
  width: 264px;
}
</style>

<style lang="scss" scoped>
  .app-container{
    &-main{
      min-height: 400px;
    }
    &-footer{
      margin-top: 20px;
      &-title{
        display: flex;
        margin-bottom: 20px;
        &-item{
          cursor: pointer;
          padding: 5px 20px;
          border-radius: 8px;
        }
        .active{
          background-color: aqua;
        }
      }
    }
  }
  .el-select{
    width: 100%;
  }
   .upload-area {
    margin: 20px 0;
    
    // 修复上传区域宽度问题
    ::v-deep .el-upload {
      width: 100%;
    }
    
    ::v-deep .el-upload-dragger {
      width: 100%;
      box-sizing: border-box;
    }
    
    // 确保提示文字与上传区域宽度一致
    ::v-deep .el-upload__tip {
      width: 100%;
      box-sizing: border-box;
      margin-top: 10px;
      text-align: left;
      display: flex;
      align-items: center;
      flex-direction: column;
      
      .el-upload__tip {
        margin-bottom: 5px;
      }
      
      span {
        display: block;
        margin-bottom: 5px;
      }
    }
  }
</style>